package com.ph.clouds.tracker;


import android.app.Application;
import android.content.Context;
import android.os.Handler;
import android.os.Looper;

import com.ph.clouds.tracker.config.TrackConfiguration;
import com.ph.clouds.tracker.db.TrackDBManager;
import com.ph.clouds.tracker.entity.TrackDevice;
import com.ph.clouds.tracker.entity.TrackParamsEntity;
import com.ph.clouds.tracker.network.IDataListener;
import com.ph.clouds.tracker.network.TrackHttpEngine;
import com.ph.clouds.tracker.util.TrackerLog;

import java.util.ArrayList;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

/**
 * @Author yushuangjiang
 * @Time 2021/8/2 11:45
 * @Description： 埋点SDK API使用类
 */
public class Tracker {

    private final String TAG = this.getClass().getSimpleName();
    public static final String SDK_VERSION = "1.0.0";
    private static Tracker INSTANCE;
    private static final Object mLock = new Object();
    private Context mContext;
    private TrackConfiguration configuration;

    //根据上传策略 启动定时器  读取DB  上传
    private final Timer mTimer = new Timer(true);

    private Tracker() {
    }

    public static Tracker getInstance() {
        if (INSTANCE == null) {
            synchronized (Tracker.class) {
                if (INSTANCE == null) {
                    INSTANCE = new Tracker();
                }
            }
        }
        return INSTANCE;
    }

    /**
     * app启动初始化
     */
    public void init(Application application, TrackConfiguration config) {
        if (config == null) {
            throw new IllegalArgumentException("TrackConfiguration can't be null");
        }
        mContext = application.getApplicationContext();
        //设置参数
        setTrackerConfig(config);
        //初始化header参数

        //修改上传策略
        changeUploadStrategy();
    }


    /**
     * 新增一条埋点数据
     */
    public void track(TrackParamsEntity entity) {
        TrackerLog.i(TAG, "新增埋点：" + entity.toString1());
        switch (configuration.getUploadCategory()) {
            case NOW:
                //请求接口 上传数据
                addCommonParams(entity);
                TrackerLog.i(TAG, "请求接口：" + entity.toString());
                TrackHttpEngine.getInstance().request(entity.toString(), configuration.getHeaderMap(), configuration.getServerUrl(),
                        new IDataListener<String>() {
                    @Override
                    public void onSuccess(String data) {
                        TrackerLog.i(TAG, data);
                    }

                    @Override
                    public void onFailure() {
                        TrackerLog.i(TAG, "track event upload fail");
                    }
                });
                break;
            case TIME_MINUTER:
                //存入本地数据库 启动定时器上传
                TrackDBManager.inserTrack(mContext, entity);
                break;
            case NEXT_LAUNCH:
                //App启动时读取所有数据上传
                TrackerLog.i(TAG, "启动时读取所有数据上传");
                break;
        }
    }


    /**
     * 设置埋点配置字段
     */
    private void setTrackerConfig(TrackConfiguration config) {
        if (config != null) {
            this.configuration = config;
        }
    }

    /**
     * 上传策略
     */
    private void changeUploadStrategy() {
        switch (configuration.getUploadCategory()) {
            case TIME_MINUTER:
                mTimer.schedule(task, 0, configuration.getMinutes() * 60 * 1000);
                //                mTimer.schedule(task, 0, 1000); //测试1秒一次
                break;
            case NEXT_LAUNCH:
                uploadTrackEventsOneTime();//启动时上传一次
                break;
            default:
                break;
        }
    }

    private boolean uploading = false;  //上传中

    static Handler sMainHandler = new Handler(Looper.getMainLooper()); //切换到ui线程

    private TimerTask task = new TimerTask() {
        @Override
        public void run() {
            if (uploading) {
                TrackerLog.i(TAG, "上一次上传还未结束");
                return;
            }
            //读取数据库未上传的数据
            List<TrackParamsEntity> mTrackList = addCommonParamsToBody(TrackDBManager.getEvents(mContext));
            TrackerLog.i(TAG, mTrackList.size() + "");
            uploading = true;
            //TODO 请求接口一次上传多条埋点数据
            sMainHandler.postDelayed(() -> {
                //TODO 上传成功后标记上传成功，删除数据
                TrackerLog.i(TAG, "上传成功");
                uploading = false;
            }, 5 * 1000);

        }
    };

    /**
     * 上传一次
     */
    private void uploadTrackEventsOneTime() {
        //读取数据库未上传的数据
        List<TrackParamsEntity> mTrackList = addCommonParamsToBody(TrackDBManager.getEvents(mContext));
        TrackerLog.i(TAG, mTrackList.size() + "");
        TrackerLog.i(TAG, "启动时上传一次成功");
    }


    /**
     * 设备信息发生变化 需要修改
     */
    public void changeDeviceInfo(TrackDevice device) {
        if (configuration == null) {
            throw new IllegalArgumentException("TrackConfiguration can't be null");
        }
        configuration.setDevice(device);
    }

    /**
     * 请求接口的时候组装设备信息参数
     */
    private List<TrackParamsEntity> addCommonParamsToBody(List<TrackParamsEntity> list) {
        if (list == null || list.size() == 0) return new ArrayList();
        for (TrackParamsEntity entity : list) {
            addCommonParams(entity);
        }
        TrackerLog.i(TAG, list.size() + "");
        return list;
    }


    private void addCommonParams(TrackParamsEntity entity) {
        entity.setAndroidId(configuration.getDevice().getAndroidId());
        entity.setDeviceModel(configuration.getDevice().getDeviceModel());
        entity.setImei(configuration.getDevice().getImei());
    }

    public TrackConfiguration getConfiguration() {
        return configuration;
    }

    public void release() {
        if (task != null && !task.cancel()) task.cancel();
    }
}
